package com.dp.system.client;

import com.alibaba.fastjson2.JSONObject;
import com.dp.system.domain.SysTemperature;
import com.dp.system.service.ISysTemperatureService;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

@Component
public class AliyunMqttClient {
    private static final String MQTT_HOST = "iot-06z00h6yp22nd5b.mqtt.iothub.aliyuncs.com";
    private static final int MQTT_PORT = 1883;
    private static final String CLIENT_ID = "hqbaqsSfNDF.water_WX|securemode=2,signmethod=hmacsha256,timestamp=1743035986252|";
    private static final String USERNAME = "water_WX&hqbaqsSfNDF";
    private static final String PASSWORD = "6ee3c5baa1e1b4e166921e74801a33d2a7f4a00cddd52dae955aea559359a1bf";

    private MqttClient mqttClient;
    private final AtomicReference<SysTemperature> latestTemperature = new AtomicReference<>();
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    @Resource
    private ISysTemperatureService sysTemperatureService;

    public void connect() {
        try {
            String serverUrl = "tcp://" + MQTT_HOST + ":" + MQTT_PORT;
            mqttClient = new MqttClient(serverUrl, CLIENT_ID, new MemoryPersistence());

            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(USERNAME);
            options.setPassword(PASSWORD.toCharArray());
            options.setCleanSession(true);
            options.setConnectionTimeout(30);
            options.setKeepAliveInterval(60);

            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void messageArrived(String topic, MqttMessage message) {
                    SysTemperature temp = parseMessage(message.getPayload());
                    if (temp != null) {
                        latestTemperature.set(temp);
                        System.out.println("更新最新温度：" + temp.getTemperatureValue());
                    }
                }

                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("连接丢失，原因：" + cause.getMessage());
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {}
            });

            mqttClient.connect(options);
            System.out.println("MQTT 连接成功，开始订阅主题");
            subscribeTopic("/hqbaqsSfNDF/water_WX/user/get");

            // 等待一段时间，让 messageArrived 有机会更新 latestTemperature
            try {
                Thread.sleep(5000); // 等待 5 秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            saveLatestTemperature();

            scheduler.scheduleAtFixedRate(this::saveLatestTemperature, 3, 3, TimeUnit.MINUTES);
            System.out.println("定时任务已启动，将每隔 3 分钟保存一次数据");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    private SysTemperature parseMessage(byte[] payload) {
        try {
            String jsonStr = new String(payload);
            JSONObject json = JSONObject.parseObject(jsonStr);
            BigDecimal tempValue = json.getBigDecimal("Temp");

            SysTemperature temperature = new SysTemperature();
            temperature.setGreenhouseId(1L);
            temperature.setTemperatureValue(tempValue);
            temperature.setRecordTime(new Date());
            return temperature;
        } catch (Exception e) {
            System.out.println("数据解析失败：" + e.getMessage());
            return null;
        }
    }

    private void saveLatestTemperature() {
        SysTemperature temp = latestTemperature.get();
        if (temp == null) {
            System.out.println("无有效数据，跳过本次保存");
            return;
        }

        SysTemperature toSave = new SysTemperature();
        toSave.setGreenhouseId(temp.getGreenhouseId());
        toSave.setTemperatureValue(temp.getTemperatureValue());
        toSave.setRecordTime(new Date());

        sysTemperatureService.insertSysTemperature(toSave);
        System.out.println("定时保存成功：" + toSave.getTemperatureValue() + "，时间：" + toSave.getRecordTime());
    }

    private void subscribeTopic(String topic) {
        try {
            mqttClient.subscribe(topic, 1);
            System.out.println("成功订阅主题：" + topic);
        } catch (MqttException e) {
            System.out.println("订阅主题失败：" + e.getMessage());
        }
    }

    public void publishMessage(String topic, String message) {
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                MqttMessage mqttMessage = new MqttMessage(message.getBytes());
                mqttClient.publish(topic, mqttMessage);
                System.out.println("消息发布成功，主题: " + topic + ", 消息内容: " + message);
            } else {
                System.out.println("MQTT 客户端未连接，无法发布消息。");
            }
        } catch (MqttException e) {
            System.out.println("消息发布失败: " + e.getMessage());
        }
    }
}